﻿using Finance.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Finance.Web.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(User user)
        {
            if (ModelState.IsValid && Membership.ValidateUser(user.Login, user.Password))
            {
                FormsAuthentication.SetAuthCookie(user.Login, false);
                return Redirect(Url.Action("Index", "Home"));
            }
            ModelState.AddModelError("error", "Неправильные данные");
            return View(user);
        }

        public ActionResult Login()
        {
            return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return Redirect(Url.Action("Index", "Home"));
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(User user)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var muser = Membership.CreateUser(user.Login, user.Password);
                    return Login(user);
                }
                catch (MembershipCreateUserException ex)
                {
                    if (ex.StatusCode == MembershipCreateStatus.DuplicateUserName)
                        ModelState.AddModelError("Login", "Уже существует пользователь с таким имененем");
                    else if (ex.StatusCode == MembershipCreateStatus.InvalidPassword)
                        ModelState.AddModelError("Password", "Неправильный пароль (пустой)");
                }
            }
            return View();
        }
    }
}
